/**
 * Jul 12, 2012
 */
package ee.tallink.common;

import javax.ws.rs.core.Response;

import ee.tallink.common.resource.ErrorInfo;

/**
 * @author andrei
 *
 */
public class ServiceException extends RuntimeException {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private ErrorInfo errorInfo = new ErrorInfo();
	private Response.Status errorStatus;
	
	public ServiceException(
			Response.Status status, 
			String description,
			String reason, 
			String internalDescription,
			Throwable cause) {
		super(description, cause);

		if( status == null ) 
			status = Response.Status.NOT_ACCEPTABLE;  //was internal
		else
			if (status == Response.Status.INTERNAL_SERVER_ERROR 
				&& cause != null) {
				if (cause.getMessage().matches("^.*Could not find resource for relative.*$"))
					status = Response.Status.NOT_FOUND;
				}
//				throw RequestError.ELEMENT_RESOURCE_NOTFOUND.build("");

		if( description == null ) description = status.getReasonPhrase();
		

		errorStatus = status;
		errorInfo.status = status.getStatusCode();
		errorInfo.description = description;
		errorInfo.reason = reason;
		errorInfo.internalDescription = internalDescription;
		if( cause != null && internalDescription == null ) errorInfo.internalDescription = cause.getMessage();
	}
	
	public ServiceException(
			Response.Status status, 
			String description,
			String reason,
			Throwable cause) {
		this( status, description, reason, null, cause);
	}
	
	public ServiceException(
			Response.Status status, 
			String description,
			Throwable cause) {
		this( status, description, null, null, cause);
	}
	
	public ServiceException(
			Response.Status status, 
			Throwable cause) {
		this( status, null, null, null, cause);
	}
	
	public ServiceException(
			Response.Status status, 
			String description,
			String reason, 
			String internalDescription) {
		this(status, description, reason, internalDescription, null);
	}
	
	public ServiceException(
			Response.Status status, 
			String description,
			String reason) {
		this(status, description, reason, null, null);
	}
	
	public ServiceException(
			Response.Status status, 
			String description) {
		this(status, description, null, null, null);
	}
	
	public ServiceException(Response.Status status) {
		this(status, null, null, null, null);
	}
	
	public ServiceException(Throwable cause) {
		this(null, null, null, null, cause);
	}
	
	public ServiceException() {
		this(null, null, null, null, null);
	}
	
	public Response.Status getStatus() {
		return errorStatus;
	}
	
	public ErrorInfo getErrorInfo() {
		return errorInfo;
	}

}
